package com.itany.corejava.code12_线程;

/**
 * @author MissChen
 * @version 1.0
 * @date 2023 年11月30日 10:16
 */
public class Test14_死锁 extends Thread {
    static Object objectA = new Object();
    static Object objectB = new Object();

    @Override
    public void run() {
        while (true) {
            if ("线程A".equals(Thread.currentThread().getName())) {
                synchronized (objectA) {
                    System.out.println("线程A拿到了A锁,准备拿B锁");
                    synchronized (objectB) {
                        System.out.println("线程A拿到了B锁，顺利执行完一轮");
                    }
                }
            } else if ("线程B".equals(Thread.currentThread().getName())) {
                synchronized (objectB) {
                    System.out.println("线程B拿到了B锁,准备拿A锁");
                    synchronized (objectA) {
                        System.out.println("线程B拿到了A锁，顺利执行完一轮");
                    }
                }
            }
        }
    }
}

class Test {
    public static void main(String[] args) {
        Test14_死锁 t1 = new Test14_死锁();
        t1.setName("线程A");
        t1.start();
        Test14_死锁 t2 = new Test14_死锁();
        t2.setName("线程B");
        t2.start();
    }
}